import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { getRequest, patchRequest, postRequest } from "@/comm/request";
import { ElMessage } from "element-plus";
import { getTmpObjects } from "@/comm/tooler";

export const useLayoutStore = defineStore("layout", () => {
  const curItem = ref<any>({type: 'stage'});
  const list = ref([]);
  const previewShow = ref(false)
  const background = ref('#ffffff')

  const init = (id)=>{
    getRequest("/api/im/page/" + id).then(res => {
      console.log("res", res)
      list.value = res.schema
    }).catch(err => {
      console.log("err", err)
    })
  }

  const chooseItem = (item) => {
    curItem.value = item;
  }

  const changeStyle = (style) => {
    curItem.value.style = {...curItem.value.style, ...style}
    console.log(curItem.value)
  }

  const changeTitleWord = (val)=>{
    curItem.value.data.title = val;
  }

  const changeDescWord = (val)=>{
    curItem.value.data.desc = val;
  }

  const changeBackground = (color) => {
    background.value = color
  }

  const changePreviewShow = (v) => {
    previewShow.value = v
  }

  const changeTempData = (title, desc, img, post)=>{
    console.log("changeTempData", curItem)
    if(curItem.value.type == 'tmp'){
      curItem.value.data.title = title
      curItem.value.data.desc = desc
      curItem.value.data.post = post
      curItem.value.data.img = img
    }
  }

  const changeTitleStyle = (style)=>{
    curItem.value.titleStyle = {...curItem.value.titleStyle, ...style}
    console.log("curItem.value",  curItem.value)
  }

  const changeDescStyle = (style)=>{
    curItem.value.descStyle = {...curItem.value.descStyle, ...style}
    console.log("curItem.value",  curItem.value)

  }

  const updatePage = (id:any)=>{
    const posts = getTmpObjects(list.value);
    patchRequest("/api/im/page/" + id, {
      schema: list.value,
      posts: posts.map(i=>i.data.post)
    }).then(res => {
      console.log("res", res)
      if (res.id) {
        ElMessage({
          message: 'Update Success',
          type: 'success',
        })
      }
    }).catch(err => {
      console.log("err", err)
      ElMessage("Error")
    })
  }

  const savePage = ()=>{
    const posts = getTmpObjects(list.value);
    postRequest("/api/im/page/", {
      schema: list.value,
      posts: posts.map(i=>i.data.post)
    }).then(res => {
      console.log("res", res)
      if (res.id) {
        ElMessage({
          message: 'Save Success',
          type: 'success',
        })
      }
    }).catch(err => {
      console.log("err", err)
      ElMessage("Error")
    })
  }

  return { changeTitleWord, changeDescWord, updatePage, savePage, curItem, chooseItem, init, changeStyle, list, previewShow, changeTitleStyle, changeDescStyle, changePreviewShow, changeTempData, background, changeBackground };
});
